package com.yuan.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuan.reggie.common.R;
import com.yuan.reggie.dto.DishDto;
import com.yuan.reggie.pojo.Category;
import com.yuan.reggie.pojo.Dish;
import com.yuan.reggie.pojo.DishFlavor;
import com.yuan.reggie.service.CategoryService;
import com.yuan.reggie.service.DishFlavorService;
import com.yuan.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author yuanxingke
 * @date 2022/8/1 20:47
 */
@RestController
@Slf4j
@RequestMapping("dish")
public class DishController {

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private DishService dishService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping
    public R<String> add(@RequestBody DishDto dishDto) {
        dishService.saveWithFlavor(dishDto);

        //清理这个分类下的菜品信息缓存
        redisTemplate.delete("dish_"+dishDto.getCategoryId());

        return R.success("添加成功");
    }


    @GetMapping("page")
    public R<Page<DishDto>> page(Integer page, Integer pageSize, String name) {

        Page<Dish> dishPage = new Page<>(page, pageSize);

        LambdaQueryWrapper<Dish> lambdaQueryWrapper = new LambdaQueryWrapper<>();

        lambdaQueryWrapper.like(StringUtils.isNotBlank(name), Dish::getName, name).orderByDesc(Dish::getUpdateTime);

        dishService.page(dishPage, lambdaQueryWrapper);

        Page<DishDto> dishDtoPage = new Page<>(page, pageSize);

        //拷贝数据
        List<DishDto> dishDtoList = new ArrayList<>();
        for (Dish dish : dishPage.getRecords()) {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(dish, dishDto);

            Category category = categoryService.getById(dish.getCategoryId());
            //设置名字
            dishDto.setCategoryName(category.getName());
            dishDtoList.add(dishDto);
        }
        //设置美味
        dishDtoPage.setRecords(dishDtoList);

        BeanUtils.copyProperties(dishPage, dishDtoPage, "records");

        return R.success(dishDtoPage);
    }


    @GetMapping("{id}")
    public R<DishDto> getById(@PathVariable Long id){
        DishDto dishDto= dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }

    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto){
        dishService.updateWithFlavor(dishDto);
        redisTemplate.delete("dish_"+dishDto.getCategoryId());


        return R.success("修改成功");
    }

    /**
     * 根据分类的id 查询对应的菜品信息
     */

    @GetMapping("list")
    public R<List<DishDto>> list(Dish dish){
        //redis缓存菜品数据
        String key = "dish_" + dish.getCategoryId();
        List<DishDto> dishDtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);
        if(dishDtoList!=null){
            return R.success(dishDtoList);
        }

        LambdaQueryWrapper<Dish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());
        lambdaQueryWrapper.eq(Dish::getStatus,1).orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> dishList = dishService.list(lambdaQueryWrapper);

        dishDtoList=new ArrayList<>();

        for (Dish dish1 : dishList) {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(dish1,dishDto);
            //查询口味
            QueryWrapper<DishFlavor> queryWrapper=new QueryWrapper<>();
            queryWrapper.eq("dish_id",dish1.getId());
            List<DishFlavor> flavors = dishFlavorService.list(queryWrapper);
            dishDto.setFlavors(flavors);
            dishDtoList.add(dishDto);
        }

        //如果不存在则保存到redis中
        redisTemplate.opsForValue().set(key,dishList,60, TimeUnit.MINUTES);
        return R.success(dishDtoList);
    }

    /**
     * 根据id删除菜品
     * @param ids
     * @return
     */
    @DeleteMapping()
    public R<String> delete(Long[] ids){
         dishService.removeWithFlavor(ids);
         return R.success("删除成功");
    }


    @PostMapping("status/{num}")
    public R<String> status(@PathVariable("num") Integer num, Long[] ids){

        Dish dish = new Dish();
        dish.setStatus(num);
        LambdaQueryWrapper<Dish> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(Dish::getId,ids);
        dishService.update(dish,lambdaQueryWrapper);
        return R.success("停售成功");
    }
}
